﻿using System;
using System.Collections.Generic;
using System.Linq;
using IterationLife.ContentResources.Models;
using IterationLife.ContentResources.Repositories;
using Util;
using Util.Datas.Ef;
using Util.Exceptions;

namespace IterationLife.Datas.Repositories.ContentResources
{
    /// <summary>
    /// 内容资源分类仓储
    /// </summary>
    public class ContentResourceCategoryRepository : RepositoryBase<ContentResourceCategory>, IContentResourceCategoryRepository
    {
        /// <summary>
        /// 初始化内容资源分类仓储
        /// </summary>
        /// <param name="unitOfWork">工作单元</param>
        public ContentResourceCategoryRepository(IApplicationUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }

        /// <summary>
        /// 根据编码集合获取启用集合编号
        /// </summary>
        /// <param name="codes">编码集合</param>
        public List<Guid?> GetEnabledIdsByCodes(string codes)
        {
            var codeList = Util.Helpers.Convert.ToList<string>(codes).Distinct().ToList();
            var entities = Find().Where(t => codeList.Contains(t.Code));
            if (entities == null || entities.Count() == 0)
                throw new Warning("编码无效");
            var resultIds = new List<Guid?>();
            foreach (var item in entities)
            {
                var id = item.Id.ToString().ToLower();
                var findEntities = Find().Where(t => t.Path.Contains(id)).ToList();
                findEntities.ForEach(t => resultIds.Add(t.Id));
            }
            return resultIds.Distinct().ToList();
        }

        /// <summary>
        /// 根据编号获取启用集合编号
        /// </summary>
        /// <param name="codes">编码集合</param>
        public List<Guid?> GetEnabledIdsById(Guid? id)
        {
            if (id.IsEmpty())
                return new List<Guid?>();
            var resultIds = new List<Guid?>();
            var findId = id.ToString().ToLower();
            var findEntities = Find().Where(t => t.Path.Contains(findId)).ToList();
            findEntities.ForEach(t => resultIds.Add(t.Id));
            return resultIds.Distinct().ToList();
        }
    }
}
